package org.kaiwo.util;

/**
 * Created by chensk on 2018/8/4.
 * 愿我出走半生,归来仍是少年
 */

import org.apache.commons.codec.binary.Base64;
import org.kaiwo.constants.Constants;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.util.Map;
import java.io.FileInputStream;
import java.security.PublicKey;import java.security.cert.Certificate;import java.security.cert.CertificateException;import java.security.cert.CertificateFactory;
import java.util.TreeMap;


/**
 * Created by Medivh on 2018/8/3.
 */
public class SignUtil {
    private File exportedFile;
    public static void main(String args[]) throws Exception {

        TreeMap<String,String> map = new TreeMap<String,String>();
        map.put("a","ss");
        map.put("b","ss");
        String sign = sign(map);

        StringBuffer sb = new StringBuffer();
        for (String key : map.keySet()) {
            if (map.get(key) != null && !map.get(key).equals(""))
                sb.append(key + "=" + map.get(key) + "&");
        }
        String queryString = sb.substring(0, sb.length() - 1);// 构造待签名字符串

        System.out.print(validate(queryString,sign));
        // export.exportCertificate();
    }

    private static PublicKey getPublicKey() {
        String pubKey = Constants.publicKeyUrl;
        InputStream in = null;
        try {
            in = new FileInputStream(pubKey);
            PublicKey publicKey = CertificateUtils.getPublicKey(in);

            return publicKey;
        } catch (Exception e) {
            System.out.print("请cer文件在指定位置");
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                // logger.error("Read public key error", e);
            }
        }
        return null;
    }
    public static boolean validate(String s, String sign) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, SignatureException {
        Signature st = Signature.getInstance("SHA1withRSA");
        PublicKey publicKey = getPublicKey();
        st.initVerify(publicKey);
        st.update(s.getBytes("UTF-8"));
        boolean result = st.verify(Base64.decodeBase64(sign.getBytes("UTF-8")));
        return result;
    }



    public static String sign(Map<String, String> resp) {
        PrivateKey privateKey = null;

        StringBuffer sb = new StringBuffer();
        for (String key : resp.keySet()) {
            if (resp.get(key) != null && !resp.get(key).equals(""))
                sb.append(key + "=" + resp.get(key) + "&");
        }
        String queryString = sb.substring(0, sb.length() - 1);// 构造待签名字符串
        FileInputStream fis = null;
        String sign = null;
        try {
            if (privateKey == null) {
                fis = new FileInputStream(Constants.privateKeyUrl);
                privateKey = CertificateUtils.getPrivateKey(fis, null, Constants.password);

            }
            Signature signature = Signature.getInstance("SHA1withRSA");
            signature.initSign(privateKey);
            signature.update(queryString.getBytes("UTF-8"));
            sign = Base64.encodeBase64String(signature.sign());
        } catch (Exception e) {
            System.out.print("请jks文件在指定位置");
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {

                }
            }
        }
        return sign;
    }

}
